#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>    // 主要的socket函数和数据结构
#include <netinet/in.h>      // IPv4和IPv6地址结构
#include <arpa/inet.h>       // 地址转换函数
#include <unistd.h>  
#include<cstring>
using namespace std;

#define NUM 1024

class TcpClient
{
public:
    TcpClient(const string &ip, const uint16_t &port)
        : _sock(-1)
        , _serverip(ip)
        , _serverport(port)
    {}
    void initClient()
    {
        //1.创建sock
        _sock = socket(AF_INET,SOCK_STREAM,0);
        if(_sock < 0)
        {
            cerr << "socket create error"<< endl;
            exit(2);
        }
        //2. tcp的客户端要不要bind?要的!要不要显示的bind?不要显示的bind
        //3. 要不要listen?不要!
        //4. 要不要accept?不要!
        //5. 要什么？要发起连接
    }
    void start()
    {
        struct sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());
        server.sin_port = htons(_serverport);

        if(connect(_sock,(struct sockaddr*)&server,sizeof(server))!=0)
        {
            cerr << "socket connect error"<<endl;
        } 
        else 
        {
            //发送
            string msg;
            while(true)
            {
                std::cout << "Enter# ";
                std::getline(std::cin, msg);
                write(_sock, msg.c_str(), msg.size());

                char buffer[NUM];
                int n = read(_sock, buffer, sizeof(buffer)-1);
                if(n > 0)
                {
                    //目前我们把读到的数据当成字符串, 截止目前
                    buffer[n] = 0;
                    std::cout << "Server回显# " << buffer << std::endl;
                }
                else
                {
                    break;
                }

            }
        }
    }
    ~TcpClient()
    {
        if(_sock>=0)
        {
            close(_sock);
        }
    }

private:
    int _sock;
    uint16_t _serverport;
    string _serverip;
};